//
//  NetworkUtils.m
//  youwei
//
//  Created by 王昭 on 2017/6/9.
//  Copyright © 2017年 xiaoningmeng. All rights reserved.
//

#import "NetworkUtil.h"
#import "LoginController.h"
#import "ZZHttpInterface.h"
#import "UIDevice-Hardware.h"

@implementation NetworkUtil

#pragma mark - GET请求
+ (void)GET:(NSString *)urlString parameters:(id)parameters success:(void (^)(id responseObject,NSDictionary *dict))success failure:(void (^)(NSError *error,NSString *message))failure
{
    
    [AFHTTPSessionManager shareManager].responseSerializer = [AFHTTPResponseSerializer serializer];
    [AFHTTPSessionManager shareManager].requestSerializer.timeoutInterval = 10.0f;
    
//    DLog(@"baseUrl:%@", baseUrl);
//    DLog(@"cookid: %@", [UserUtil getUser].token);
    
    NSMutableDictionary *params = nil;
    if([parameters isKindOfClass:[NSMutableDictionary class]]){
        params = parameters;
    }else{
        params = [[NSMutableDictionary alloc] initWithDictionary:parameters];
    }
    [params setObject:getNowDateTimeLong() forKey:@"ts"];
    [params setObject:@"3.0.0" forKey:@"ver"];
    [params setObject:[UIDevice currentDevice].getIOSUUID forKey:@"udid"];
    if(urlString!=nil){
        if([urlString rangeOfString:@"?"].length>0){
            urlString=[NSString stringWithFormat:@"%@&ts=%@&udid=%@&ver=3.0.0&sign=%@",urlString,params[@"ts"],params[@"udid"],[self getSignParamByDict:params]];
        }else{
            urlString=[NSString stringWithFormat:@"%@?ts=%@&udid=%@&ver=3.0.0&sign=%@",urlString,params[@"ts"],params[@"udid"],[self getSignParamByDict:params]];
        }
    }
    
    DLog(@"baseUrl:%@", urlString);
    DLog(@"cookid: %@", [UserUtil getUser].user_sign);
    //在请求头中
    [[AFHTTPSessionManager shareManager].requestSerializer setValue:[NSString stringWithFormat:@"sign=%@",[UserUtil getUser].user_sign] forHTTPHeaderField:@"cookie"];
    
    //添加请求基本参数
    [[AFHTTPSessionManager shareManager] GET:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        if (success) {
            success(responseObject,dictionary);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error,@"");
        }
    }];
}

#pragma mark - POST请求
+ (void)POST:(NSString *)urlString parameters:(id)parameters success:(void (^)(id responseObject,NSDictionary *dict))success failure:(void (^)(NSError *error,NSString *message))failure
{
    NSMutableDictionary *params = nil;
    if([parameters isKindOfClass:[NSMutableDictionary class]]){
        params = parameters;
    }else{
        params = [[NSMutableDictionary alloc] initWithDictionary:parameters];
    }
    [params setObject:getNowDateTimeLong() forKey:@"ts"];
    [params setObject:@"3.0.0" forKey:@"ver"];
    [params setObject:[UIDevice currentDevice].getIOSUUID forKey:@"udid"];
    [params setObject:[self getSignParamByDict:params] forKey:@"sign"];
    
    DLog(@"baseUrl:%@\n%@", urlString,params);
//    DLog(@"cookid: %@", [UserUtil getUser].user_id);
    
    [AFHTTPSessionManager shareManager].requestSerializer = [AFHTTPRequestSerializer serializer];
    [AFHTTPSessionManager shareManager].responseSerializer = [AFHTTPResponseSerializer serializer];
    [AFHTTPSessionManager shareManager].requestSerializer.timeoutInterval = 10.0f;
    [AFHTTPSessionManager shareManager].responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", @"image/jpeg", nil];

    //在请求头中
//    [[AFHTTPSessionManager shareManager].requestSerializer setValue:[NSString stringWithFormat:@"token=%@",[UserUtil getUser].token] forHTTPHeaderField:@"cookie"];
//    DLog(@"token:%@", [UserUtil getUser].token);
    
    //添加请求基本参数
    [[AFHTTPSessionManager shareManager] POST:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        DLog(@"url:%@\n%@",task.currentRequest.URL,[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if([dictionary[@"status"] integerValue] == kNetworkLoginCode){
            if (success) {
                success(responseObject,dictionary);
            }
//
//            [UserUtil deleteUser];
//            [PatientUtil deletePatient];
//
//            [PopUtil showMessage:responseObject[@"msg"] positionType:PopPositionTypeMiddle];
//
//            BaseNaviController *navi = [[BaseNaviController alloc] initWithRootViewController:[[LoginController alloc] init]];
//            [UIApplication sharedApplication].delegate.window.rootViewController = navi;
//            return;
        }else{
            if (failure) {
                failure(nil,dictionary[@"msg"]);
            }
        }
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        DLog(@"failure---url:%@",task.response.URL);
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        DLog(@"str:%@",str);
    
        if (failure) {
            failure(error,str);
        }
    }];
}

#pragma mark - POST UPLOAD上传图片
+ (void)uploadPost:(NSString *)urlString parameters:(id)parameters UploadImage:(NSArray *)imageArray success:(void (^)(id responseObject))success failure:(void (^)(NSError *error,NSString *message))failure
{
    //添加请求基本参数
    [AFHTTPSessionManager shareManager].responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg", nil];
    [AFHTTPSessionManager shareManager].responseSerializer = [AFHTTPResponseSerializer serializer];
    [AFHTTPSessionManager shareManager].requestSerializer.timeoutInterval = 20.0f;
    [[AFHTTPSessionManager shareManager] POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (UIImage *image in imageArray) {
            NSData *data = UIImageJPEGRepresentation(image, 0.7);
            //第一个是对应的是服务器端的字段，第二个是文件名，第三个是图片格式
            [formData appendPartWithFileData:data name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if([dictionary[@"code"] integerValue] == kNetworkLoginCode){
            [UserUtil deleteUser];
            [PatientUtil deletePatient];
            
            [PopUtil showMessage:responseObject[@"message"] positionType:PopPositionTypeMiddle];
            
            BaseNaviController *navi = [[BaseNaviController alloc] initWithRootViewController:[[LoginController alloc] init]];
            [UIApplication sharedApplication].delegate.window.rootViewController = navi;
            return;
        }
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error,@"");
        }
    }];
}

#pragma mark - 上传文件
+ (void)uploadPost:(NSString *)urlString parameters:(id)parameters file:(NSData *)upData success:(void (^)(id responseObject))success failure:(void (^)(NSError *error,NSString *message))failure
{
    NSString * fname = [NSString stringWithFormat:@"image100%ld.jpg",(long)[NSDate date].timeIntervalSince1970];
//    checkPathAndCreate(getDocumentsFilePath(@"/qqplaygroup/"));
//    NSString *fullPath=getDocumentsFilePath([NSString stringWithFormat:@"/qqplaygroup/%@",fname]);
//    [upData writeToFile:fullPath atomically:YES];
    NSMutableDictionary *params = nil;
    if([parameters isKindOfClass:[NSMutableDictionary class]]){
        params = parameters;
    }else{
        params = [[NSMutableDictionary alloc] initWithDictionary:parameters];
    }
    [params setObject:getNowDateTimeLong() forKey:@"ts"];
    [params setObject:@"3.0.0" forKey:@"ver"];
    [params setObject:[UIDevice currentDevice].getIOSUUID forKey:@"udid"];
    [params setObject:[self getSignParamByDict:params] forKey:@"sign"];
    
     DLog(@"baseUrl:%@\n%@", urlString,params);
    //添加请求基本参数
    [AFHTTPSessionManager shareManager].responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"application/octet-stream", nil];
    [AFHTTPSessionManager shareManager].responseSerializer = [AFHTTPResponseSerializer serializer];
    [AFHTTPSessionManager shareManager].requestSerializer.timeoutInterval = 20.0f;
    [[AFHTTPSessionManager shareManager] POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        [formData appendPartWithFileURL:[NSURL URLWithString:fullPath] name:@"image" fileName:fname mimeType:@"file" error:nil];
        [formData appendPartWithFileData:upData name:@"image" fileName:fname mimeType:@"image/jpeg"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if([dictionary[@"status"] integerValue] == kNetworkLoginCode){
            if (success) {
                success(dictionary);
            }
            //
            //            [UserUtil deleteUser];
            //            [PatientUtil deletePatient];
            //
            //            [PopUtil showMessage:responseObject[@"msg"] positionType:PopPositionTypeMiddle];
            //
            //            BaseNaviController *navi = [[BaseNaviController alloc] initWithRootViewController:[[LoginController alloc] init]];
            //            [UIApplication sharedApplication].delegate.window.rootViewController = navi;
            //            return;
        }else{
            if (failure) {
                failure(nil,dictionary[@"msg"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        DLog(@"str:%@",str);
        
        if (failure) {
            failure(error,str);
        }
    }];
}


/*
 //上传文件参数
 UIImage *iamge = [UIImage imageNamed:@"123.png"];
 NSData *data = UIImagePNGRepresentation(iamge);
 //这个就是参数
 [formData appendPartWithFileData:data name:@"file" fileName:@"123.png" mimeType:@"image/png"];
 */

#pragma mark - POST UPLOAD上传文件
+ (void)uploadPost:(NSString *)urlString parameters:(id)parameters UploadFilePath:(NSString *)filePath success:(void (^)(id responseObject))success failure:(void (^)(NSError *error,NSString *message))failure
{
    [AFHTTPSessionManager shareManager].requestSerializer.timeoutInterval = 20.f;
    [AFHTTPSessionManager shareManager].responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",nil];
    [AFHTTPSessionManager shareManager].responseSerializer = [AFHTTPResponseSerializer serializer];
    [[AFHTTPSessionManager manager] POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传文件操作
        NSData *data = [NSData dataWithContentsOfFile:filePath];
        //filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`,
        [formData appendPartWithFileData:data name:@"chapter_message_content" fileName:filePath mimeType:@"file"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if([dictionary[@"status"] integerValue] == kNetworkLoginCode){
            if (success) {
                success(dictionary);
            }
            //
            //            [UserUtil deleteUser];
            //            [PatientUtil deletePatient];
            //
            //            [PopUtil showMessage:responseObject[@"msg"] positionType:PopPositionTypeMiddle];
            //
            //            BaseNaviController *navi = [[BaseNaviController alloc] initWithRootViewController:[[LoginController alloc] init]];
            //            [UIApplication sharedApplication].delegate.window.rootViewController = navi;
            //            return;
        }else{
            if (failure) {
                failure(nil,dictionary[@"msg"]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSData *data = error.userInfo[@"com.alamofire.serialization.response.error.data"];
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        DLog(@"str:%@",str);
        
        if (failure) {
            failure(error,str);
        }
    }];
}


#pragma mark - 网络检测
+ (void)ReachabilityStatus:(void (^)(id status))netStatus{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                if (netStatus) {
                    netStatus(@"0");  //未知网络
                }
                break;
            case AFNetworkReachabilityStatusNotReachable:
                if (netStatus) {
                    netStatus(@"0");  //无可用网络
                }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                if (netStatus) {
                    netStatus(@"1");  //WI-FI
                }
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                if (netStatus) {
                    netStatus(@"2");  //蜂窝流量
                }
                break;
            default:
                break;
        }
    }];
    [manager startMonitoring];
}



+(NSArray *) dictSortByKey:(NSDictionary *) dict{
    // 因为NSDictionary排序
    //    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    //    [dict setObject:@"3" forKey:@"key3"];
    //    [dict setObject:@"1" forKey:@"key1"];
    //    [dict setObject:@"4" forKey:@"key4"];
    //    [dict setObject:@"2" forKey:@"key2"];
    //    for (NSString *str in [dict allKeys]) {
    //        NSLog(@"key == %@",str);
    //    }
    
    NSArray *keys = [dict allKeys];
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    return sortedArray;
}

+(NSString *) getSignParamByDict:(NSDictionary *) dict{
    NSString *commenKey = @"c9ab853af97a886b5953ed3c2b177f8b";
    NSArray *sortedArray = [self dictSortByKey:dict];
    
    NSString *sign = @"";
    for (NSString *key in sortedArray) {
        if(sign.length == 0){
            sign = [sign stringByAppendingString:[NSString stringWithFormat:@"%@=%@",key,dict[key]]];
        }else{
            sign = [sign stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",key,dict[key]]];
        }
    }
    //    sign = [sign substringFromIndex:1];
    DLog(@"排序自动：%@",sign);
    //    [ZCLogUtils logHeader:LogHeader debug:@"sign:%@",sign];
    sign = [NSString stringWithFormat:@"%@%@%@",commenKey,sign,commenKey];
    DLog(@"添加key:%@",sign);
    return [md5(sign) lowercaseString];
}



@end
